/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : pop_join.js                                 
*  Description  : 참여자 설정하기
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-15  김효순    Created. 
*  2012-04-10  김효순    Complete. 
*******************************************************************************/
jQuery(function($){
	// 신청자 리스트
	function clsApplyList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._ERRMSG = {
			"_NODATA": "신청자가 없습니다."
			, "_NOVALUE": "참여승인할 신청자를 선택해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsApplyList.prototype = {
		_init: function(){
			var $layer = $("div.left:eq(0)");
			$layer.find("li:first span:first img").width(35).height(35);
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("li:first").clone(true)
			}
			
			this.setList([]);
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, concatList: function(thisData){
			if(!thisData) return;
			if(thisData.length < 1) return;
			this.listData = this.listData.concat(thisData);
			this.display();
		}
		, setApplyMember: function(thisData){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["아이디"] == thisData["아이디"]) break;
			}
			
			if(i<this.listData.length){
				this.listData[i]["이미지"] =  thisData["이미지"];
				this.listData[i]["성별"] =  thisData["성별"];
				this.listData[i]["핸디"] =  thisData["핸디"];
				this.listData[i]["평균타수"] =  thisData["평균타수"];
				
				this.displayMember(i);
			}
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element =this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("img[alt='조인룸 신청자']").next("span").html("(" + this.listData.length + ")");
			
			$layer.find("dd:first>ul").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("dd:first>ul").append($element.clone(true));
			}
			$layer.find("dd:first>ul>li").each(function(n){
				$(this).find("span:first img").attr("src", _gf.filePath2Url(thisClass.listData[n]["이미지"])).unbind("error").error(function(){
					$(this).attr("src", _gf.getDefaultProfileImage());
				});
				$(this).find("span.point_b").html(thisClass.listData[n]["닉네임"]);
				$(this).find("ul.info_num li:eq(0)").html(thisClass.listData[n]["성별"] ? thisClass.listData[n]["성별"]:"");
				$(this).find("ul.info_num li:eq(1) span").html(thisClass.listData[n]["핸디"] ? thisClass.listData[n]["핸디"]:"0");
				$(this).find("ul.info_num li:eq(2) span").html(thisClass.listData[n]["평균타수"] ? thisClass.listData[n]["평균타수"]:"0");
			});
		}
		, displayMember: function(n){
			var $obj = this._HTMLDom["$layer"].find("dd:first>ul>li:eq(" + n + ")");
			
			$obj.find("span:first img").attr("src", _gf.filePath2Url(this.listData[n]["이미지"])).unbind("error").error(function(){
				$(this).attr("src", _gf.getDefaultProfileImage());
			});
			$obj.find("ul.info_num li:eq(0)").html(this.listData[n]["성별"]);
			$obj.find("ul.info_num li:eq(1) span").html(this.listData[n]["핸디"]);
			$obj.find("ul.info_num li:eq(2) span").html(this.listData[n]["평균타수"]);
		}
		, spinStart: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("dd>ul").hide();
			if($layer.find("div#tmpSpin").length == 0){
				$layer.find("dd").append("<div id='tmpSpin' style='position:relative; width:400px; height:200px;' />");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("div#tmpSpin").hide().spin(false);
			$layer.find("dd>ul").show();
		}
		, getError: function(){
			if(this.errMsg) return this._ERRMSG[this.errMsg];
			return null;
		}
		, valid: function(){
			var $layer = this._HTMLDom["$layer"];
			var ckCount = $layer.find("input:checkbox").length;
			var ckedCount = $layer.find("input:checkbox:checked").length;
			
			this.errMsg = null;

			if(ckCount == 0){
				this.errMsg = "_NODATA";
				return false;
			}else if(ckedCount == 0){
				this.errMsg = "_NOVALUE";
				return false;
			}
			
			return true;
		}
		, getIdList: function(){
			return $.map(this.listData, function(objValue, i){
				return objValue["아이디"];
			});
		}
		, $getBtnAgree: function(){
			return this._HTMLDom["$layer"].find("img[alt='참여승인']");
		}
		, getCheckedList: function(){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;
			
			var aRet = [];
			
			$layer.find("input:checkbox:checked").each(function(){
				var n = $layer.find("input:checkbox").index($(this));
				
				aRet.push(thisClass.listData[n]);
			});
			
			for(var i=0;i<aRet.length;i++){
				for(j=0;j<this.listData.length;j++){
					if(aRet[i]["아이디"] == this.listData[j]["아이디"]){
						this.listData.splice(j, 1);
						break;
					}
				}
			}
			
			this.display();
			
			return aRet;
		}
	}
	
	// 참여자 리스트
	function clsJoinList()
	{
		this._HTMDom = null;
		this.listData = null;
		
		this._ERRMSG = {
			"_NODATA": "참여자가 없습니다."
			, "_NOVALUE": "참여취소할 참여자를 선택해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsJoinList.prototype = {
		_init: function(){
			var $layer = $("div.left:eq(1)");
			$layer.find("li:first span:first img").width(35).height(35);
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("li:first").clone(true)
			}
			
			this.setList([]);
		}
		, setList:clsApplyList.prototype.setList
		, concatList: clsApplyList.prototype.concatList
		, setJoinMember: clsApplyList.prototype.setApplyMember
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element =this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("img[alt='조인룸 참여자']").next("span").html("(" + this.listData.length + ")");
			
			$layer.find("dd:first>ul").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("dd:first>ul").append($element.clone(true));
			}
			
			$layer.find("dd:first>ul>li").each(function(n){
				$(this).find("span:first img").attr("src", _gf.filePath2Url(thisClass.listData[n]["이미지"])).unbind("error").error(function(){
					$(this).attr("src", _gf.getDefaultProfileImage());
				});
				$(this).find("span.point_b").html(thisClass.listData[n]["닉네임"]);
				$(this).find("ul.info_num li:eq(0)").html(thisClass.listData[n]["성별"] ? thisClass.listData[n]["성별"]:"");
				$(this).find("ul.info_num li:eq(1) span").html(thisClass.listData[n]["핸디"] ? thisClass.listData[n]["핸디"]:"0");
				$(this).find("ul.info_num li:eq(2) span").html(thisClass.listData[n]["평균타수"] ? thisClass.listData[n]["평균타수"]:"0");
			});
		}
		, displayMember: clsApplyList.prototype.displayMember
		, spinStart: clsApplyList.prototype.spinStart
		, spinEnd: clsApplyList.prototype.spinEnd
		, getError: clsApplyList.prototype.getError
		, valid: clsApplyList.prototype.valid
		, getIdList: clsApplyList.prototype.getIdList
		, $getBtnCancel: function(){
			return this._HTMLDom["$layer"].find("img[alt='참여취소']");
		}
		, getCheckedList: clsApplyList.prototype.getCheckedList
	}
	
	function clsMemberList()
	{
		this.applyList = null;
		this.joinList = null;
	}
	
	clsMemberList.prototype = {
		setApplyList: function(thisData){
			if(!this.applyList) this.applyList = [];
			this.applyList.push(thisData);
		}
		, setJoinList: function(thisData){
			if(!this.joinList) this.joinList = [];
			this.joinList.push(thisData);
		}
		, getAgreeValue: function(joinList){
			var r = [];
			
			for(var i=0;i<joinList.length;i++){
				if($.inArray(joinList[i], this.joinList) == -1){
					r.push(joinList[i]);
				}
			}
			
			return r;
		}
		, getCancelValue: function(applyList){
			var r = [];
			
			for(var i=0;i<applyList.length;i++){
				if($.inArray(applyList[i], this.applyList) == -1){
					r.push(applyList[i]);
				}
			}
			
			return r;
		}
	}
	
	
	
	function clsComm()
	{
		this.joinroomKey = null;
		
		// 신청자 리스트
		this.applyList = null;
		// 참여자 리스트
		this.joinList = null;
	}
	
	clsComm.prototype = {
		_init: function(){
			
		}
		, setJoinroomKey: function(val){
			this.joinroomKey = val;
		}
		, getJoinroomInfo: function(arg){
			var thisClass = this;
			
			arg = arg || {};
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "getDetailJoinRoom";
			_gf.ajax({
				"sid":"JR001",
				"servicename":serviceName,
				"listcount":1,
				"currpageno":1
			}, {
				"joinRoomSeq": this.joinroomKey
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "결과값": {}
				}
				
				var items = ret["msp"]["contents"]["items"]
				
				if(items){
					var obj = items

					var myState = "미신청";
					switch(obj["joinStatus"]){
						case "S":
							myState = "부킹장";
							break;
						case "A":
							myState = "신청완료";
							break;
						case "P":
							myState = "참여완료";
							break;
					}
					
					var szStat = "";
					switch(obj["procStatus"].trim()){
						case "C":
							szStat = "진행중";
							break;
						case "D":
							szStat = "조인마감";
							break;
						case "E":
							szStat = "조인완료";
							break;
					}
					
					var szSmoke = "";
					switch(_util.nvl(obj["smokeYn"]).trim()){
						case "Y":
							szSmoke = "흡연";
							break;
						case "N":
							szSmoke = "비흡연";
							break;
					}
					
					res["결과값"] = {
						"작성일": _util.nvl(obj["reserveDate"])
						, "작성요일": _util.nvl(obj["bookingDay"])
						, "작성시": _util.nvl(obj["bookingTime"])
						, "작성자": _util.nvl(obj["bookUserId"])
						, "골프장코스": _util.nvl(obj["golfClubInfo"])
						, "홀명": _util.nvl(obj["holeInfo"])
						, "비밀여부": (obj["openYn"] == "Y") ? false:true
						, "인사말": _util.enter2br(_util.nvl(obj["ment"]))
						, "내상태코드": _util.nvl(obj["joinStatus"])
						, "내상태": myState
						, "신청자수": _util.nvl(obj["applycnt"])+"명"
						, "참여자수": _util.nvl(obj["particnt"])+"명"
						, "본인참여": _util.nvl(obj["joinYn"]).trim()
						, "참여조건": {
							"성별": _util.nvl(obj["sex"]).trim()
							, "연령대": _util.nvl(obj["age"]).trim()
							, "평균타수": _util.nvl(obj["aVerage"]).trim()
							, "흡연": szSmoke
						}
						, "진행상황": szStat
						, "초대회원수": _util.nvl(obj["memCount"])
						, "예약자명": _util.nvl(obj["rUserName"])
						, "조인룸상태코드": _util.nvl(obj["procStatus"])
						, "조인룸상태": _util.nvl(obj["procStatusNm"])
						, "초대인원": _util.nvl(obj["invitCnt"], 0)
					}
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
		, getApplyList: function(){
			var thisClass = this;
			
			//ajax
			var serviceName = "getApplyMemberList";
			document.objGlobal.ajax({
				"sid": "JR001"
				, "servicename": serviceName
				, "listcount": 1000
				, "currpageno": 1
			}, {
				"joinRoomSeq": this.joinroomKey
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				thisClass.applyList = [];
				
				var genders = {
					"M": "남자"
					, "F": "여자"
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						thisClass.applyList.push({
							"아이디": obj["participantId"]
							, "이미지": ""
							, "닉네임": obj["nickName"]
							, "성별": genders[obj["sex"]]
							, "핸디": obj["handi"]
							, "평균타수": obj["aVerage"]
						});
					}
				}
				
				document.objControl.finishApplyList(res);
			});
		}
		, getApplyData: function(){
			return this.applyList;
		}
		, getJoinList: function(){
			var thisClass = this;
			
			//ajax
			var serviceName = "getMemberList";
			document.objGlobal.ajax({
				"sid": "JR001"
				, "servicename": serviceName
				, "listcount": 1000
				, "currpageno": 1
			}, {
				"joinRoomSeq": this.joinroomKey
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				thisClass.joinList = [];
				
				var genders = {
					"M": "남자"
					, "F": "여자"
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						thisClass.joinList.push({
							"아이디": obj["participantId"]
							, "이미지": ""
							, "닉네임": obj["nickName"]
							, "성별": genders[obj["sex"]]
							, "핸디": obj["handi"]
							, "평균타수": obj["aVerage"]
						});
					}
				}
				
				document.objControl.finishJoinList(res);
			});
		}
		, getJoinData: function(){
			return this.joinList;
		}
		// 참여승인
		, joinAgree: function(arg){
			var thisClass = this;
			
//			arg = {
//				"조인룸키": null
//				, "아이디들": null
//			}
			
			//ajax
			var serviceName = "updateMember";
			document.objGlobal.ajax({
				"sid": "JR001"
				, "servicename": serviceName
			}, {
				"joinRoomSeq": arg["조인룸키"]
				, "participantId": arg["아이디들"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				document.objControl.finishJoinAgree(res);
			});
		}
		// 참여취소
		, joinCancel: function(arg){
			var thisClass = this;
			
//			arg = {
//				"조인룸키": null
//				, "아이디들": null
//			}
			
			//ajax
			var serviceName = "deleteMember";
			document.objGlobal.ajax({
				"sid": "JR001"
				, "servicename": serviceName
			}, {
				"joinRoomSeq": arg["조인룸키"]
				, "participantId": arg["아이디들"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				document.objControl.finishJoinCancel(res);
			});
		}
	}
	
	function clsControl()
	{
		this.objComm = null;
		this.objApplyList = null;
		this.objJoinList = null;
		this.objMemberList = null;
		
		this.joinroomKey = null;
		this.joinroomInfo = null;
		
		this.agreeCount = 0;
		this.cancelCount = 0;
	}
	
	clsControl.prototype = {
		_init: function(){
			var thisClass = this;
			
			if(!opener) self.close();
			if(!opener.document.objControl) self.close();
			
			this.joinroomKey = opener.document.objControl.getJoinroomKey();
			
			if(!this.joinroomKey) self.close();
			
			//this.joinroomKey = 1097;
			
			this.objComm = new clsComm();
			this.objApplyList = new clsApplyList();
			this.objJoinList = new clsJoinList();
			this.objMemberList = new clsMemberList();
			
			this._bind();
			
			this.objComm.setJoinroomKey(this.joinroomKey);
			
			// 신청자 리스트
			this.objApplyList.spinStart();
			this.objComm.getApplyList();
			
			// 참여자 리스트
			this.objJoinList.spinStart();
			this.objComm.getJoinList();
			
			// 조인룸 정보
			_gf.spinStart();
			this.objComm.getJoinroomInfo({
				"콜백": function(ret){
					thisClass.finishJoinroomInfo(ret);
				}
			});
			
			_util.setWindowSize();
		}
		, _bind: function(){
			var thisClass = this;
			
			// 참여승인
			this.objApplyList.$getBtnAgree().click(function(){
				if(!thisClass.objApplyList.valid()){
					alert(thisClass.objApplyList.getError());
					return;
				}
				
				var memberList = thisClass.objApplyList.getCheckedList();
				thisClass.objJoinList.concatList(memberList);
				
				
			});
			
			// 참여취소
			this.objJoinList.$getBtnCancel().click(function(){
				if(!thisClass.objJoinList.valid()){
					alert(thisClass.objJoinList.getError());
					return;
				}
				
				var memberList = thisClass.objJoinList.getCheckedList();
				thisClass.objApplyList.concatList(memberList);
				
				
			});
			
			// 확인
			$("img[alt='확인']").click(function(){
				var applyList = thisClass.objApplyList.getIdList();
				var joinList = thisClass.objJoinList.getIdList();
				
				var agreeIds = thisClass.objMemberList.getAgreeValue(joinList);
				var cancelIds = thisClass.objMemberList.getCancelValue(applyList);
				
				if(joinList.length > thisClass.joinroomInfo["초대인원"]){
					alert("조인룸 참여자는 초대인원 " + thisClass.joinroomInfo["초대인원"] + "명을 넘을 수 없습니다.");
					return;
				}
				
				document.objGlobal.spinStart("sending...");
				
				for(var i=0;i<agreeIds.length;i++){
					thisClass.agreeCount++;
					thisClass.objComm.joinAgree({
						"조인룸키": thisClass.joinroomKey
						, "아이디들":agreeIds[i]
					});
				}
				
//				if(agreeIds.length){
//					thisClass.startAgree = true;
//					thisClass.objComm.joinAgree({
//						"조인룸키": thisClass.joinroomKey
//						, "아이디들":agreeIds
//					});
//				}

				for(var i=0;i<cancelIds.length;i++){
					thisClass.cancelCount++;
					thisClass.objComm.joinCancel({
						"조인룸키": thisClass.joinroomKey
						, "아이디들": cancelIds[i]
					});
				}
				
//				if(cancelIds.){
//					thisClass.startCancel = true;
//					thisClass.objComm.joinCancel({
//						"조인룸키": thisClass.joinroomKey
//						, "아이디들": cancelIds
//					});
//				}
				
				if(!(thisClass.agreeCount || thisClass.cancelCount)){
					thisClass.close();
				}
			});
			
			//  취소
			$("img[alt='취소'], img[alt='close']").click(function(){
				self.close();
			});
		}
		// 신청자 완료
		, finishApplyList: function(ret){
			var thisClass = this;
			
			this.objApplyList.spinEnd();
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisData = this.objComm.getApplyData();
			
			for(var i=0;i<thisData.length;i++){
				thisClass.objMemberList.setApplyList(thisData[i]["아이디"]);
				
				document.objGlobal.getMemberInfo({
					"아이디": thisData[i]["아이디"]
					, "콜백": function(ret, info, args){
						thisClass.objApplyList.setApplyMember(info);
					}
				});
			}
			
			this.objApplyList.setList(thisData);
		}
		// 참여자 완료
		, finishJoinList: function(ret){
			var thisClass = this;
			
			this.objJoinList.spinEnd();
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisData = this.objComm.getJoinData();
			
			for(var i=0;i<thisData.length;i++){
				thisClass.objMemberList.setJoinList(thisData[i]["아이디"]);
				
				document.objGlobal.getMemberInfo({
					"아이디": thisData[i]["아이디"]
					, "콜백": function(ret, info, args){
						thisClass.objJoinList.setJoinMember(info);
					}
				});
			}
			this.objJoinList.setList(thisData);
		}
		// 참여승인 완료
		, finishJoinAgree: function(ret){
			this.agreeCount--;
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			if(!(this.agreeCount || this.cancelCount)) this.close();
		}
		// 참여취소 완료
		, finishJoinCancel: function(ret){
			this.cancelCount--;
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			if(!(this.agreeCount || this.cancelCount)) this.close();
		}
		// 조인룸 정보 완료
		, finishJoinroomInfo: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			
			this.joinroomInfo = ret["결과값"];
		}
		, close: function(){
			if(opener.document.objControl.closeJoin) opener.document.objControl.closeJoin(self);
			self.close();
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});